//
//  BabySetViewController.m
//  Toyohu
//
//  Created by GuoPeng on 16/4/21.
//  Copyright © 2016年 celia. All rights reserved.
//

#import "BabySetViewController.h"
#import "UIView+Fillet.h"
#import "GPCustomMD.h"
#import <Masonry/Masonry.h>
#import <ReactiveCocoa.h>
#import <IQKeyboardManager.h>
#import "FlatButton.h"

#import "GPCustomMD.h"
#import "GPAFNetworking3.h"

#import "TYH_LoginLoginModel.h"
#import "LoginManager.h"
#import "CYLTabBarControllerConfig.h"

@interface BabySetViewController ()
{
    UIDatePicker *_datePicker;
    FlatButton *hiddenButton;
}

@property (weak, nonatomic) IBOutlet UITextField *motherTextField;
@property (weak, nonatomic) IBOutlet UITextField *babyTextField;
@property (weak, nonatomic) IBOutlet UITextField *dateOfBirthTextField;
@property (weak, nonatomic) IBOutlet UIButton *maleButton;
@property (weak, nonatomic) IBOutlet UIButton *femaleButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIImageView *selectImage1;
@property (weak, nonatomic) IBOutlet UIImageView *selectImage2;

@property (nonatomic, copy) NSArray *textFieldArray;

@property (weak, nonatomic) IBOutlet UIButton *dateOfBirthButton;
@property (weak, nonatomic) IBOutlet UIImageView *userImg;
@property (weak, nonatomic) IBOutlet UIImageView *babyImg;
@property (weak, nonatomic) IBOutlet UIImageView *dateImg;


@end

@implementation BabySetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    [self bindEvents];
//    [self isLogin];
}

- (void)isLogin
{
    if ([[LoginManager shareLoginManager] isLoggedin]) {
        UIStoryboard *mainTabBarStoryboard = [UIStoryboard storyboardWithName:@"MainTabBar" bundle:nil];
        UITabBarController  * mainTabBar = [mainTabBarStoryboard instantiateViewControllerWithIdentifier:@"MainTabBarID"];
        [[[UIApplication sharedApplication] keyWindow] setRootViewController:mainTabBar];
        return;
    }
}

- (void)viewHigher
{
    [self hiddenDatePikcer];
}

- (void)bindEvents
{
    @weakify(self);
    RAC(self.saveButton,enabled) = [RACSignal combineLatest:@[self.motherTextField.rac_textSignal,self.babyTextField.rac_textSignal] reduce:^(NSString *motherText,NSString *babyText){
        @strongify(self);
        if (self.dateOfBirthTextField.text.length > 5) {
            if (motherText.length && babyText.length ) {
                self.saveButton.alpha = 1;
                return @YES;
            } else {
                self.saveButton.alpha = 0.5;
                return @NO;
            }
        } else {
            self.saveButton.alpha = 0.5;
            return @NO;
        }
    }];
}

- (void)initView
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewHigher) name:UIKeyboardWillShowNotification object:nil];
    
    self.dateOfBirthTextField.enabled = NO;
    self.selectImage2.hidden = YES;
    [self.bgView filletWithBounds:UIRectCornerTopLeft | UIRectCornerTopRight  cornerRadiiSize:CGSizeMake(8.0f, 8.0f)];
    self.textFieldArray = @[_motherTextField,_babyTextField,_dateOfBirthTextField];
    
    self.saveButton.clipsToBounds = YES;
    self.saveButton.layer.cornerRadius = HEIGHT_HALF(self.saveButton);
    self.saveButton.layer.borderColor = [UIColor whiteColor].CGColor;
    self.saveButton.layer.borderWidth = 2.0f;
    
    _datePicker = [[UIDatePicker alloc] init];
    _datePicker.backgroundColor = [UIColor whiteColor];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    _datePicker.maximumDate = [NSDate date];
    [self.view addSubview:_datePicker];
    [_datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(self.view).multipliedBy(0.5);
    }];
    _datePicker.hidden = YES;
    [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    
    hiddenButton = [FlatButton button];
    [hiddenButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    hiddenButton.hidden = YES;
    [self.view addSubview:hiddenButton];
    hiddenButton.backgroundColor = [UIColor yellowColor];
    [hiddenButton setTitle:@"完成" forState:UIControlStateNormal];
    [hiddenButton addTarget:self action:@selector(hiddenDatePikcer) forControlEvents:UIControlEventTouchUpInside];
    [hiddenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_datePicker);
        make.bottom.equalTo(_datePicker.mas_top);
        make.width.equalTo(@60);
        make.height.equalTo(@40);
    }];
    
    self.userImg.image = [UIImage imageNamed:@"user-1"];
    self.babyImg.image = [UIImage imageNamed:@"baby-2"];
    self.dateImg.image = [UIImage imageNamed:@"age-3"];
}

- (void)hiddenDatePikcer
{
    _datePicker.hidden = YES;
    hiddenButton.hidden = YES;
    [self showSaveBtn];
}

- (void)dateChanged:(UIDatePicker *)datePicker
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    self.dateOfBirthTextField.text = [dateFormatter stringFromDate:datePicker.date];
}

- (void)showSaveBtn
{
    if (self.motherTextField.text.length && self.babyTextField.text.length && self.dateOfBirthTextField.text.length) {
        self.saveButton.alpha = 1;
        self.saveButton.enabled = YES;
    }
}

- (IBAction)setDateClick:(id)sender
{
    
    [self showSaveBtn];
    
    _datePicker.hidden = NO;
    hiddenButton.hidden = NO;
    [self hiddenKeyBoary];
}

- (IBAction)maleClick:(id)sender
{
    self.selectImage1.hidden = NO;
    self.selectImage2.hidden = YES;
    GPSET(@"男", @"baby_gender");
    
}

- (IBAction)femaleClick:(id)sender
{
    self.selectImage1.hidden = YES;
    self.selectImage2.hidden = NO;
    GPSET(@"女", @"baby_gender");

}

- (void)hiddenKeyBoary
{
    for (UITextField *textFiedld in self.textFieldArray) {
        [textFiedld resignFirstResponder];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hiddenKeyBoary];
}

- (IBAction)saveClick:(id)sender
{
    NSString *pid = [[(NSDictionary *)GPGET(@"loginInfo") objectForKey:@"msg"] objectForKey:@"pId"];

    [SVProgressHUD showWithStatus:@"正在保存，请稍等..." maskType:SVProgressHUDMaskTypeGradient];
    
    [GPAFNetworking3 post:AddInfo parameters:@{@"info":[GPAFNetworking3 dictionaryToJson:@{@"pId":pid,@"nickName":self.motherTextField.text,@"children":@[@{@"cName":self.babyTextField.text,@"cSex":self.selectImage1.hidden?@"0":@"1",@"cBirthday":self.dateOfBirthTextField.text}]}]} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nullable responseObject) {
        TYH_LoginLoginModel *model = [[TYH_LoginLoginModel alloc] initWithDictionary:responseObject];
        if (model.code == 1) {
            
//            UIStoryboard *mainTabBarStoryboard = [UIStoryboard storyboardWithName:@"MainTabBar" bundle:nil];
//            UITabBarController  * mainTabBar = [mainTabBarStoryboard instantiateViewControllerWithIdentifier:@"MainTabBarID"];
//            [[[UIApplication sharedApplication] keyWindow] setRootViewController:mainTabBar];
////            [[[UIApplication sharedApplication] keyWindow] setRootViewController:[MainTabBarController new]];
            
            CYLTabBarControllerConfig *tabBarControllerConfig = [[CYLTabBarControllerConfig alloc] init];
            [[[UIApplication sharedApplication] keyWindow] setRootViewController:tabBarControllerConfig.tabBarController];

        } else {
            SHOW_ERROR
        }
    } failure:^(NSString * _Nonnull errorLD) {
//        [SVProgressHUD showErrorWithStatus:errorLD maskType:SVProgressHUDMaskTypeGradient];
        SHOW_NTERROR
    }];
    
    GPSET(self.motherTextField.text, @"mother_nickname")
    GPSET(self.babyTextField.text, @"baby_nickname")
    GPSET(self.dateOfBirthTextField.text, @"baby_dateOfBirth")
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
